package com.hzp.format;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import de.hunsicker.jalopy.Jalopy;

public class Formatter {
	private static Jalopy jalopy = null;

	private static Jalopy getJalopy() throws IOException {
		if (jalopy == null) {
			Jalopy.setConvention(Formatter.class.getResource("/com/hzp/format/formatter.xml"));
			jalopy = new Jalopy();
		}
		return jalopy;
	}

	public static void copyFiles(File from, File dest) throws IOException {
		if (dest == null) {
			return;
		}
		if (from.isDirectory()) {
			for (File sub : from.listFiles()) {
				copyFiles(sub, new File(dest.getAbsolutePath() + "/" + sub.getName()));
			}
		} else {
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			byte[] buffer = new byte[1024];
			InputStream input = null;
			OutputStream output = null;
			try {
				input = new FileInputStream(from);
				output = new FileOutputStream(dest);
				int length = -1;
				while ((length = input.read(buffer)) >= 0) {
					output.write(buffer, 0, length);
				}
			} finally {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			}
		}
	}

	public static void format(File from, File dest) throws IOException {
		if (!from.exists()) {
			throw new IOException("输入路径不存在：" + from.getAbsolutePath());
		}
		if (dest != null) {
			copyFiles(from, dest);
		} else {
			dest = from;
		}
		format(dest);
	}

	public static void format(File file) throws IOException {
		if (!file.exists()) {
			throw new IOException("输入路径不存在：" + file.getAbsolutePath());
		}
		if (file.isDirectory()) {
			for (File sub : file.listFiles()) {
				format(sub);
			}
		} else if (file.getName().endsWith(".java")) {
			Jalopy jalopy = getJalopy();
			jalopy.setInput(file);
			jalopy.setOutput(file);
			jalopy.format();
		}
	}

	private static String readLine(Scanner scanner, boolean canBeNull) throws IOException {
		do {
			String line = scanner.nextLine();
			if (line == null) {
				throw new IOException("输入已关闭");
			}
			line = line.trim();
			if (line.length() > 0) {
				return line;
			}
		} while (!canBeNull);
		return null;
	}

	public static void console() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("欢迎使用Java代码格式化工具");
		try {
			while (true) {
				System.out.print("请输入源码路径（回车结束）：");
				String from = readLine(scanner, false);
				System.out.print("请输入目的路径（为空则使用源码目录，回车结束）：");
				String dest = readLine(scanner, true);
				try {
					format(new File(from), dest == null ? null : new File(dest));
					System.out.println("格式化成功.");
				} catch (Exception e) {
					System.out.println("格式化失败：" + e.getMessage());
				}
				System.out.println();
			}
		} catch (IOException e) {
		}
	}

	public static void main(String[] args) throws IOException {
		console();
	}
}